package com.example.flutter_study

import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
import androidx.core.app.JobIntentService
import org.greenrobot.eventbus.EventBus
import java.util.*

class TimeService : JobIntentService() {
    var mTimer: Timer? = null
    val TAG = "TimeService"
    var count = 0

    override fun onHandleWork(intent: Intent) {
        TODO("Not yet implemented")
    }

    //只有第一次开启服务才会调用
    override fun onCreate() {
        super.onCreate()

    }

    override fun onBind(intent: Intent): IBinder? {
        return MyBind()
    }

    class MyBind : Binder() {
        fun getService(): TimeService {
            return TimeService()
        }
    }

    //每次开启服务都会调用
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        count = 0
        mTimer = Timer()
        mTimer?.schedule(object : TimerTask() {
            override fun run() {
                count++
                EventBus.getDefault().post(count.toString())
            }
        }, 0, 1000)
        return super.onStartCommand(intent, flags, startId)

    }

    override fun onDestroy() {
        super.onDestroy()
        mTimer?.cancel()
    }

}